home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Cream of the Crop 3
/
Cream of the Crop 3.iso
/
comm
/
wnos5src.zip
/
PATHNAME.C
< prev
next >
Wrap
C/C++ Source or Header
|
1993-10-03
|
3KB
|
130 lines
#include <stdio.h>
#include "global.h"
#include "dirutil.h"
/* Process a path name string, starting with and adding to
* the existing buffer
*/
static void near
crunch(char *buf,char *path)
{
char *cp = buf + strlen(buf); /* Start write at end of current buffer */
/* Now start crunching the pathname argument */
for(;;){
/* Strip leading /'s; one will be written later */
while(*path == '/')
path++;
/* no more, all done */
if(*path == '\0')
break;
/* Look for parent directory references, either at the end
* of the path or imbedded in it
*/
if(strcmp(path,"..") == 0 || strncmp(path,"../",3) == 0) {
/* Hop up a level */
if((cp = strrchr(buf,'/')) == NULLCHAR) {
/* Don't back up beyond root */
cp = buf;
}
/* In case there's another .. */
*cp = '\0';
/* Skip ".." */
path += 2;
/* Skip one or more slashes */
while(*path == '/') {
path++;
}
} else if(*path == '.' || strncmp(path,"./",2) == 0) {
/* "no op" */
/* Skip "." */
path++;
/* Skip one or more slashes */
while(*path == '/')
path++;
} else {
/* Ordinary name, copy up to next '/' or end of path */
*cp++ = '/';
while(*path != '/' && *path != '\0')
*cp++ = *path++;
}
}
*cp++ = '\0';
}
/* Given a working directory and an arbitrary pathname, resolve them into
* an absolute pathname. Memory is allocated for the result, which
* the caller must free
*/
char *
pathname(char *cd,char *path)
{
char *buf, *tbuf, *cp, c;
int tflag = 0;
if(cd == NULLCHAR || path == NULLCHAR)
return NULLCHAR;
/* If path has any backslashes, make a local copy with them
* translated into forward slashes
*/
if(strchr(path,'\\') != NULLCHAR) {
tflag = 1;
cp = tbuf = mxallocw(strlen(path));
while((c = *path++) != '\0'){
if(c == '\\') {
*cp++ = '/';
} else {
*cp++ = c;
}
}
*cp = '\0';
path = tbuf;
}
/* Strip any leading white space on args */
while(*cd == ' ' || *cd == '\t')
cd++;
while(*path == ' ' || *path == '\t')
path++;
/* Allocate and initialize output buffer; user must free */
buf = mxallocw(strlen(cd) + strlen(path) + 10); /* fudge factor */
/* Interpret path relative to cd only if it doesn't begin with "/" */
if(*path != '/')
crunch(buf,cd);
crunch(buf,path);
/* Special case: null final path means the root directory */
if(buf[0] == '\0') {
if(cd[1] == ':') {
strncpy(buf,cd,4);
buf[3] = '\0';
} else {
buf[0] = '/';
buf[1] = '\0';
}
}
if(tflag)
xfree(tbuf);
if(buf[2] == ':') {
if(buf[3] == '\0') {
buf[3] = '/';
buf[4] = '\0';
}
cp = strxdup(&buf[1]);
xfree(buf);
buf = cp;
}
return buf;
}